const config = require('../config')
const User_col = require('../models/user')
const Pass_col = require('../models/password')
const Article_col = require('../models/article')
const crypt = require('../utils/bcrypt')
const { v1: uuidv1 } = require('uuid')
const jwt = require('../utils/jwt')
const formatTime = require('../utils/formatTime')
const { marked } = require('marked')
const { ifError } = require('assert')

//登录注册接口
const login = async (ctx, next) => {
    const { account, password, islogin } = ctx.request.body

    if (islogin) {//如果是登录

        const one = await User_col.findOne({ account: account })

        if (one) {
            const passOne = await Pass_col.findOne({ userId: one.userId })

            //获取加密的hash与登录密码做比较
            await crypt.valitate(password, passOne.hash).then(async (res) => {
                if (res) {
                    let token = await jwt.sign({
                        id: one.userId,
                        account: account,
                        isAdmin: one.isAdmin
                    })
                    ctx.body = {
                        code: 1,
                        msg: '登录成功',
                        data: {
                            isAdmin: one.isAdmin,
                            token: token,
                            account: account
                        }
                    }
                } else {
                    ctx.body = {
                        code: 0,
                        msg: '密码错误'
                    }
                }
            })
        } else {
            ctx.body = {
                code: 0,
                msg: '账号不存在'
            }
        }

    } else {//如果是注册
        const res = await User_col.findOne({ account: account })
        if (res) {
            ctx.body = {
                code: 0,
                msg: '这个账号已经有人注册了'
            }
        } else {
            let userId = uuidv1()
            const newUser = await User_col.create({
                account,
                userId
            })
            if (newUser) {
                await crypt.encrypt(password, config.saltTimes).then(async (hash) => {
                    const newPass = await Pass_col.create({
                        userId,
                        hash
                    })
                    if (newPass) {
                        ctx.body = {
                            code: 1,
                            msg: '注册成功'
                        }
                    } else {
                        await User_col.deleteOne({
                            account: account
                        })
                        ctx.body = {
                            code: 0,
                            msg: '注册失败，稍后再试'
                        }
                    }
                })
            } else {
                ctx.body = {
                    code: 0,
                    msg: '注册失败，稍后再试'
                }
            }
        }
    }
}

//写文章
const create = async (ctx, next) => {
    const params = ctx.request.body

    //获取格式化时间
    let time = formatTime(params.time)

    const res = await Article_col.create({
        title: params.title,
        content: params.text,
        type: params.check,
        time: time,
        username: params.userName
    })
    if (res) {
        ctx.body = {
            code: 1,
            msg: '文章发布成功'
        }
    }
}
//获取文章列表
const getArticles = async (ctx, next) => {
    const allArticles = await Article_col.find()
    ctx.body = {
        code: 1,
        data: {
            allArticles: allArticles,
        }
    }
}
// 获取文章内容
const getContent = async (ctx, next) => {
    const params = ctx.request.body
    const res = await Article_col.findOne({
        _id: params._id
    })

    await Article_col.updateOne({ _id: params._id }, {
        $set: {
            browseCount: res.browseCount + 1
        }
    })
    console.log(res);
    if (res) {
        let content = marked(res.content)
        res.content = content
        ctx.body = {
            code: 1,
            data: res
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '文章找不到'
        }
    }
}
// 删除文章
const deleteArticle = async (ctx, next) => {
    const _id = ctx.request.body._id
    const res = await Article_col.deleteOne({
        _id: _id
    })
    if (res.deletedCount > 0) {
        ctx.body = {
            code: 1,
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '删除失败'
        }
    }
}
// 点赞
const dianzan = async (ctx, next) => {
    const { _id, account } = ctx.request.body

    const res = await User_col.findOne({ account: account })
    const article = await Article_col.findOne({ _id: _id })

    const likes = res.likes
    let thumbCount = article.thumbCount
    let index = likes.indexOf(_id)

    if (index === -1) {
        likes.push(_id)
        thumbCount++
    } else {
        likes.splice(index, 1)
        thumbCount--
    }

    await User_col.updateOne({ account: account }, {
        $set: {
            likes
        }
    })
    await Article_col.updateOne({ _id: _id }, {
        $set: {
            thumbCount
        }
    })
    ctx.body = {
        code: 1
    }
}
// 评论
const publishComments = async (ctx, next) => {
    const params = ctx.request.body
    const res = await Article_col.findOne({ _id: params._id })
    let comments = res.comments

    // 如果是文章一级评论
    if (params.accountB === '') {
        let cId = uuidv1()
        params.cId = cId
        params.formatDate = formatTime(params.date)
        params.reply = []
        comments.unshift(params)
    }
    // 如果是文章二级评论
    else {
        // console.log(comments);
        // console.log(params);
        params.formatDate = formatTime(params.date)
        comments.forEach((item, index) => {
            console.log(item, index);
            if (item.cId && item.cId === params.cId) {
                item.reply.push(params)
            }
        })
    }
    await Article_col.updateOne({ _id: params._id }, { $set: { comments } })
    ctx.body = {
        code: 1
    }
}
module.exports = {
    login,
    create,
    getArticles,
    getContent,
    deleteArticle,
    dianzan,
    publishComments
}